﻿
Namespace Xml

    Public Class XmlValidator

        Private _xsdPath As String
        Private _xmlContent As String

        Private _valid As Boolean
        Private _message As String
        Private _exception As Exception

        Public Sub New(ByVal xsdPath As String, ByVal xmlContent As String)
            _xsdPath = xsdPath
            _xmlContent = xmlContent

            Call InternalInitialize()

        End Sub

#Region "Properties"

        Public Property XsdPath As String
            Get
                Return _xsdPath
            End Get
            Set(ByVal value As String)
                _xsdPath = value
                Call InternalInitialize()
            End Set
        End Property


        Public Property XmlContent As String
            Get
                Return _xmlContent
            End Get
            Set(ByVal value As String)
                _xmlContent = value
                Call InternalInitialize()
            End Set
        End Property


        Public ReadOnly Property Valid As Boolean
            Get
                Return _valid
            End Get
        End Property

        Public ReadOnly Property Message As String
            Get
                Return _message
            End Get
        End Property

        Public ReadOnly Property [Exception] As Exception
            Get
                Return _exception
            End Get
        End Property

#End Region

#Region "Private Methods"

        Private Sub InternalInitialize()

            _valid = False
            _message = String.Empty
            _exception = Nothing

        End Sub

        Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)

            _valid = False
            _message = e.Message
            _exception = e.Exception

        End Sub

#End Region


#Region "Public Methods"

        Public Sub Validate()

            _valid = True

            Dim xsd As System.Xml.Schema.XmlSchema = _
                System.Xml.Schema.XmlSchema.Read( _
                    System.Xml.XmlReader.Create(_xsdPath), _
                                                New System.Xml.Schema.ValidationEventHandler(AddressOf ValidationEventHandler))


            Dim xmlDocument As New System.Xml.XmlDocument
            xmlDocument.LoadXml(_xmlContent)
            xmlDocument.Schemas.Add(xsd)

            xmlDocument.Validate(New System.Xml.Schema.ValidationEventHandler(AddressOf ValidationEventHandler))


        End Sub

#End Region


    End Class

End Namespace